package myjava.xml;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class RssParse {

   public static void main(String[] args) {

      Document doc = getRemoteDoc("http://www.timeout.com/rss/london/music-whatson");
      Element root = (Element) doc.getDocumentElement();

      Element channel = (Element) root.getElementsByTagName("channel").item(0);

      String channelTitle = channel.getElementsByTagName("title").item(0).getTextContent();
      String channelLink = channel.getElementsByTagName("link").item(0).getTextContent();
      String channelDesc = channel.getElementsByTagName("description").item(0).getTextContent();

      printChannelDetails(channelTitle, channelLink, channelDesc);

      NodeList items = root.getElementsByTagName("item");

      for (int i = 0; i < items.getLength(); i++) {
         printArticle((Element) items.item(i));
      }
   }

   static Document getRemoteDoc(String url) {

      try {
         URL source = new URL(url);
         HttpURLConnection conn = (HttpURLConnection) source.openConnection();
         InputStream is = conn.getInputStream();
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         factory.setIgnoringComments(true);
         factory.setIgnoringElementContentWhitespace(true);
         // factory.setValidating(true);
         DocumentBuilder builder = factory.newDocumentBuilder();
         return (Document) builder.parse(new InputSource(is));
      } catch (Exception e) {
         e.printStackTrace();
         return null;
      }
   }

   static void printChannelDetails(String title, String link, String description) {
      System.out.println("CHANNEL DATA");
      System.out.println("channel title : " + title);
      System.out.println("channel link : "  + link);
      System.out.println("channel desc : " + description);
      System.out.println("-------------------");
      System.out.println("-------------------");
   }

   static void printArticle(Element n) {

      String title = n.getElementsByTagName("title").item(0).getTextContent();
      String link = n.getElementsByTagName("link").item(0).getTextContent();
      String desc = n.getElementsByTagName("description").item(0).getTextContent();
      String date = n.getElementsByTagName("pubDate").item(0).getTextContent();
      String cat = n.getElementsByTagName("category").item(0).getTextContent();

      System.out.println(title);
      System.out.println(link);
      System.out.println(desc);
      System.out.println(date);
      System.out.println(cat);
      System.out.println("-------------------");
   }
}
